package constant.milk.cashbook.sms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.bean.BankData;
import constant.milk.cashbook.bean.CheckData;
import constant.milk.cashbook.bean.CreditData;
import constant.milk.cashbook.bean.GiftData;
import constant.milk.cashbook.bean.PhoneData;
import constant.milk.cashbook.bean.RealData;
import constant.milk.cashbook.bean.SmsData;
import constant.milk.cashbook.bean.SmsInputData;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbAdapter;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.insert.AssetChoiceActivity;
import constant.milk.cashbook.insert.AssetListActivity;
import constant.milk.cashbook.select.SelectMainActivity;
import constant.milk.cashbook.sms.parser.SmsParser;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkTextView;
import constant.milk.cashbook.util.MilkUtil;

public class SmsPastListActvitiy extends SuperActivity
{
	public static final int REQUEST_SMS_INSERT = 0;
	public static final int ASSET_CHOICE_REQUEST_CODE = 1;
	public static final int ASSET_LIST_REQUEST_CODE = 2;
	
	public static final String YEAR1_DATA = "YEAR1_DATA";
	public static final String MONTH1_DATA = "MONTH1_DATA";
	public static final String DAY1_DATA = "DAY1_DATA";
	public static final String YEAR2_DATA = "YEAR2_DATA";
	public static final String MONTH2_DATA = "MONTH2_DATA";
	public static final String DAY2_DATA = "DAY2_DATA";

	private View assetView;
	private TextView assetTextView;
	private View assetNameView;
	private TextView assetNameTextView;
	private TextView selectCountTextView;
	private CheckBox allCheckBox;
	private ListView listView;
	private Button saveButton;
	
	private SmsAdapter adapter;
	
	private int year1;
	private int month1;
	private int day1;
	
	private int year2;
	private int month2;
	private int day2;
	
	private MilkManager assetManager;
	
	private ArrayList<SmsData> resultList;
	
	private String am_pm;
	private String hour;
	private String minute;
	
	private ArrayList<String> assetNameList;
	
	private int outCount;
	private int inCount;
	private int moveCount;
	private int failCount;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sms_past_list_activity);
		
		setTitle("지난문자목록");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		assetView = findViewById(R.id.smsPastAssetView);
		assetTextView = (TextView) findViewById(R.id.smsPastAssetTextView);
		assetNameView = findViewById(R.id.smsPastAssetNameView);
		assetNameTextView = (TextView) findViewById(R.id.smsPastAssetNameTextView);
		selectCountTextView = (TextView) findViewById(R.id.smsPastSelectCountTextView);
		allCheckBox = (CheckBox) findViewById(R.id.smsPastAllCheckbox);
		listView = (ListView) findViewById(R.id.listView);
		saveButton = (Button) findViewById(R.id.saveButton);
	}

	@Override
	protected void setOnClick()
	{
		assetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, SmsAssetActivity.class);
				intent.putExtra(SmsAssetActivity.ASSET_CHOICE_DATA, assetTextView.getText().toString());
				startActivityForResult(intent, ASSET_CHOICE_REQUEST_CODE);
			}
		});
		
		assetNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startAssetNameList();
			}
		});
		
		allCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				for (int i = 0; i < resultList.size(); i++)
				{
					SmsData data = resultList.get(i);
					
					if (isChecked)
					{
						data.setCheckFlag(1);
					}
					else
					{
						data.setCheckFlag(0);
					}
				}
				
				listView.setOnItemClickListener(onItemClickListener);
				
				adapter = new SmsAdapter(
						superContext, R.layout.sms_past_list_item, resultList);
				listView.setAdapter(adapter);
				
				setSelectCount();
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!checkInsert())
				{
					return;
				}
				
				String massage = setSaveData();
				
				if (massage.equals(""))
				{
					MilkUtil.showDialog(superContext, "알림", "분석에 성공한 문자가 하나도 없습니다. 문자 내용을 개발자에게 메일로 보내주세요.");
					return;
				}
				else
				{
					MilkUtil.showDialogFinish(superContext, "알림", massage);
					return;
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		new ShowDialog().execute(0);
	}
	
	private void setSelectCount()
	{
		int count = 0;
		
		for (int i = 0; i < resultList.size(); i++)
		{
			if (resultList.get(i).getCheckFlag() == 1)
			{
				count++;
			}
		}
		
		selectCountTextView.setText(count + "");
	}
	
	private void startAssetNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, assetNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, assetTextView.getText().toString());
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void setAssetNameData(String str)
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		assetNameList = new ArrayList<String>();
		
		if (str.equals(getString(R.string.realAsset)))
		{
			ArrayList<RealData> list = query.getRealList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("현금을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.bankAsset)))
		{
			ArrayList<BankData> list = query.getBankList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("통장을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.checkCardAsset)))
		{
			ArrayList<CheckData> list = query.getCheckList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("체크카드를 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.creditCardAsset)))
		{
			ArrayList<CreditData> list = query.getCreditList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("신용카드를 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.phoneAsset)))
		{
			ArrayList<PhoneData> list = query.getPhoneList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("핸드폰을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.giftCardAsset)))
		{
			ArrayList<GiftData> list = query.getGiftList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("상품권을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
	}
	
	private boolean checkInsert()
	{
		int count = Integer.parseInt(selectCountTextView.getText().toString());
		
		if (count < 1)
		{
			MilkUtil.showToast(superContext, "선택 된 문자가 하나도 없습니다.");
			return false;
		}
		
		if (assetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해 주세요.");
			return false;
		}
		
		if (assetTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "연결 자산이 없습니다. 자산관리에서 자산을 추가해주세요.");
			return false;
		}
		
		return true;
	}
	
	private String setSaveData()
	{
		String massage = "";
		outCount = 0;
		inCount = 0;
		moveCount = 0;
		failCount = 0;
		
		for (int i = 0; i < resultList.size(); i++)
		{
			if (resultList.get(i).getCheckFlag() == 1)
			{
				setSmsParserData(resultList.get(i).getMemo(), resultList.get(i).getAddress(),
						resultList.get(i).getDate());
			}
		}
		
		if (outCount != 0)
		{
			massage += "지출 문자 " + outCount;
		}
		
		if (inCount != 0)
		{
			if (massage != "")
			{
				massage += ", ";
			}
			
			massage += "수입 문자 " + inCount;
		}
		
		if (moveCount != 0)
		{
			if (massage != "")
			{
				massage += ", ";
			}
			
			massage += "이동 문자  " + moveCount;
		}
		
		if (failCount != 0)
		{
			if (massage != "")
			{
				massage += ", ";
			}
			
			massage += "입력 실패 문자  " + failCount;
		}
		
		if (massage != "")
		{
			massage += " 가 처리 되었습니다.";
		}
		
		return massage;
	}
	
	private void setSmsParserData(String body, String address, String date)
	{
		SmsParser parser = new SmsParser(body);
		
		SmsInputData inputData = parser.messageParsing();
		
		if (inputData == null || parser.getAvailable() == false) 
		{
			failCount++;
			return;
		}
		
		inputData.setDate(date);
		
		int type = parser.getSmsType();
		
		if (type == -1 || type == SmsParser.HALBU_SMS)
		{
			failCount++;
			return;
		}
		
		DbAdapter db = DbAdapter.getInstance();
		
		SmsData data = new SmsData();
		data.setAsset(assetManager.getAssetStr(assetTextView.getText().toString()));
		data.setCardname(assetNameTextView.getText().toString());
		
		if (data.getAsset().equals("") || data.getCardname().equals(""))
		{
			return;
		}
		
		boolean resultFlag = false;
		
		if (data.getAsset().equals(assetManager.getAssetStr(getString(R.string.creditCardAsset))))
		{
			if (type == SmsParser.OUT_SMS)
			{
				resultFlag = setInOutNormalData(superContext, db, data, inputData, 4);
			}
			else if (type == SmsParser.OUT_ATM_SMS)
			{
				resultFlag = setInOutMoveData(superContext, db, data, inputData);
			}
		}
		else if (data.getAsset().equals(assetManager.getAssetStr(getString(R.string.checkCardAsset))))
		{
			if (type == SmsParser.IN_SMS)
			{
				resultFlag = setInOutNormalData(superContext, db, data, inputData, 1);
			}
			else if (type == SmsParser.OUT_SMS)
			{
				resultFlag = setInOutNormalData(superContext, db, data, inputData, 0);
			}
			else if (type == SmsParser.IN_ATM_SMS)
			{
				resultFlag = setInOutMoveData(superContext, db, data, inputData);
			}
			else if (type == SmsParser.OUT_ATM_SMS)
			{
				resultFlag = setInOutMoveData(superContext, db, data, inputData);
			}
		}
		else if (data.getAsset().equals(assetManager.getAssetStr(getString(R.string.bankAsset))))
		{
			if (type == SmsParser.IN_SMS)
			{
				resultFlag = setInOutNormalData(superContext, db, data, inputData, 1);
			}
			else if (type == SmsParser.OUT_SMS)
			{
				resultFlag = setInOutNormalData(superContext, db, data, inputData, 0);
			}
			else if (type == SmsParser.IN_ATM_SMS)
			{
				resultFlag = setInOutMoveData(superContext, db, data, inputData);
			}
			else if (type == SmsParser.OUT_ATM_SMS)
			{
				resultFlag = setInOutMoveData(superContext, db, data, inputData);
			}
		}
		
		
		if (resultFlag == false)
		{
			return;
		}
		
		switch (type)
		{
			case SmsParser.IN_SMS:
				inCount++;
				break;
			case SmsParser.OUT_SMS:
				outCount++;
				break;
			case SmsParser.IN_ATM_SMS:
				moveCount++;
				break;
			case SmsParser.OUT_ATM_SMS:
				moveCount++;
				break;
			default:
				break;
		}
	}
	
	private boolean setInOutNormalData(Context context, DbAdapter db, SmsData data, SmsInputData inputData, int flag)
	{
		DbInsertQuery query = null;
		MilkManager milkManager = null;
		
		try
		{
			milkManager = new MilkManager(context, db);
			query = new DbInsertQuery(context, db);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (flag == 0)
			{
				map.put("type", "0");
				map.put("subcategory", context.getString(R.string.out));
			}
			else if (flag == 1)
			{
				map.put("type", "1");
				map.put("subcategory", context.getString(R.string.in));
			}
			else if (flag == 4)
			{
				map.put("type", "4");
				map.put("subcategory", context.getString(R.string.cardcost));
			}
			
			map.put("kind", "0");
			
			map.put("asset", data.getAsset());
			map.put("name", data.getCardname());
			map.put("maincategory", "문자자동화");
			map.put("date", inputData.getDate());
			
			setNowTime();
			map.put("ampm", MilkUtil.getAmPm(am_pm));
			map.put("timehour", hour);
			map.put("timeminute", minute);
			
			map.put("money", inputData.getMoney());
			map.put("memo", inputData.getMemo1());
			
			query.setInOut(map);
			
			if (flag == 0)
			{
				milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
						inputData.getMoney(), 0);
			}
			else
			{
				milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
						inputData.getMoney(), 1);
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setInOutMoveData(Context context, DbAdapter db, SmsData data, SmsInputData inputData)
	{
		DbInsertQuery query = null;
		MilkManager milkManager = null;
		
		try
		{
			milkManager = new MilkManager(context, db);
			query = new DbInsertQuery(context, db);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("type", "2");
			map.put("kind", "0");
			
			map.put("asset", data.getAsset());
			map.put("subasset", data.getSubAsset());
			map.put("name", data.getCardname());
			map.put("subname", data.getSubCardname());
			
			map.put("maincategory", "문자자동화");
			map.put("subcategory", map.put("subcategory", context.getString(R.string.move)));
			map.put("date", inputData.getDate());
			
			setNowTime();
			map.put("ampm", MilkUtil.getAmPm(am_pm));
			map.put("timehour", hour);
			map.put("timeminute", minute);
			
			map.put("money", inputData.getMoney());
			map.put("memo", inputData.getMemo1());
			
			query.setInOut(map);
			
			milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
					inputData.getMoney(), 0);
			
			milkManager.setAssetMoney(milkManager.getAssetId(data.getSubAsset()), data.getSubCardname(),
					inputData.getMoney(), 1);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private void setNowTime()
	{
		Calendar cal = Calendar.getInstance();
		
		if (cal.get(Calendar.AM_PM) == Calendar.AM)
		{
			am_pm = "AM";
		}
		else
		{
			am_pm = "PM";
		}
		
		if (cal.get(Calendar.HOUR) == 0)
		{
			hour = "12";
		}
		else
		{
			if (cal.get(Calendar.HOUR) < 10)
			{
				hour = "0" + cal.get(Calendar.HOUR);
			}
			else
			{
				hour = cal.get(Calendar.HOUR) + "";
			}
		}
		
		if (cal.get(Calendar.MINUTE) < 10)
		{
			minute = "0" + cal.get(Calendar.MINUTE);
		}
		else
		{
			minute = cal.get(Calendar.MINUTE) + "";
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			SmsData data = (SmsData) arg0.getItemAtPosition(position);
			if (data.getCheckFlag() == 0)
			{
				data.setCheckFlag(1);
			}
			else
			{
				data.setCheckFlag(0);
			}
			
			adapter.notifyDataSetChanged();
			
			setSelectCount();
		}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == REQUEST_SMS_INSERT)
		{
			setResult(Activity.RESULT_OK);
			finish();
		}
		else if (requestCode == ASSET_CHOICE_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetChoiceActivity.ASSET_CHOICE_DATA);
			assetTextView.setText(str);
			
			setAssetNameData(str);
			
		}
		else if (requestCode == ASSET_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			assetNameTextView.setText(str);
		}
	}

	private class SmsAdapter extends ArrayAdapter<SmsData>
	{
		public SmsAdapter(Context context, int textViewResourceId, ArrayList<SmsData> objects) 
		{
			super(context, textViewResourceId, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.sms_past_list_item, null);
			}
			
			SmsData data = getItem(position);
			
			MilkTextView date = (MilkTextView) v.findViewById(R.id.smsPastItemDateTextView);
			MilkTextView address = (MilkTextView) v.findViewById(R.id.smsPastItemAddressTextView);
			MilkTextView message = (MilkTextView) v.findViewById(R.id.smsPastItemMessageTextView);
			CheckBox checkbox = (CheckBox) v.findViewById(R.id.smsPastItemCheckbox);
			
			date.setText(MilkUtil.getDateButton(data.getDate()));
			address.setText(data.getAddress());
			message.setText(data.getMemo());
			
			if (data.getCheckFlag() == 1)
			{
				checkbox.setChecked(true);
			}
			else
			{
				checkbox.setChecked(false);
			}
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>
	{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			dialog = new ProgressDialog(SmsPastListActvitiy.this);
			dialog.setCancelable(false);
			dialog.setMessage("불러오는중...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) 
		{
			if (arg0[0] == 0) 
			{
				assetManager = new MilkManager(superContext, superDb);
				
				Calendar cal1 = Calendar.getInstance();
				Calendar cal2 = Calendar.getInstance();
				
				Intent intent = getIntent();
				
				year1 = intent.getIntExtra(SelectMainActivity.YEAR1_DATA, cal1.get(Calendar.YEAR));
				month1 = intent.getIntExtra(SelectMainActivity.MONTH1_DATA, cal1.get(Calendar.MONTH));
				day1 = intent.getIntExtra(SelectMainActivity.DAY1_DATA, cal1.get(Calendar.DAY_OF_MONTH));
				year2 = intent.getIntExtra(SelectMainActivity.YEAR2_DATA, cal2.get(Calendar.YEAR));
				month2 = intent.getIntExtra(SelectMainActivity.MONTH2_DATA, cal2.get(Calendar.MONTH));
				day2 = intent.getIntExtra(SelectMainActivity.DAY2_DATA, cal2.get(Calendar.DAY_OF_MONTH));
				
				cal1.set(year1, month1, day1);
				cal2.set(year2, month2, day2);
				
				if (year1 == year2 & month1 == month2 & day1 == day2)
				{
					cal1.add(Calendar.DAY_OF_MONTH, -1);
				}
				
				SmsGet smsGet = new SmsGet(superContext);
				resultList = smsGet.getSms(cal2.getTimeInMillis(), cal1.getTimeInMillis());
				
				return 0;
			}
			
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) 
		{
			super.onPostExecute(result);

			if (dialog != null) 
			{
				dialog.dismiss();
			}
			
			if (result == 0)
			{
				listView.setOnItemClickListener(onItemClickListener);
				
				adapter = new SmsAdapter(
						superContext, R.layout.sms_past_list_item, resultList);
				listView.setAdapter(adapter);
				
				setSelectCount();
				
				assetTextView.setText(getString(R.string.creditCardAsset));
				setAssetNameData(assetTextView.getText().toString());
				
				allCheckBox.setChecked(true);
			}
		}
	}
	
	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_AUTO_PAST_SMS_LIST);
		startActivity(intent);
	}
}
